package com.rising.online.controller;

import com.rising.online.bean.CompilerBean;
import com.rising.online.bean.DynamicCompilationExecutor;
import com.rising.online.bean.DynamicCompileJavaFileObject;
import com.rising.online.service.CompilerService;
import com.rising.online.util.DynamicCompilerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.tools.JavaFileObject;
import java.util.Map;
import java.util.concurrent.*;

@RestController
public class DynamicCompilationController {

    @Autowired
    private CompilerService compilerService;
    private ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1);

    @PostMapping(value = "dynamic")
    public String dynamicController(@RequestParam("sent") String data) {
        String code = data;
        String className = DynamicCompilerUtil.getFullClassName(code);
        CompilerBean compilerBean = new CompilerBean(className, code, "", 0, 0);
        Future<Map<String, Object>> future = fixedThreadPool.submit(new DynamicCompilationExecutor(compilerService, compilerBean));
        Map<String, Object> map = null;
        String rtnString = "";
        try {
            map = future.get(3000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            rtnString = "中断异常：" + e.getMessage();
        } catch (ExecutionException e) {
            rtnString = "执行异常：" + e.getMessage();
        } catch (TimeoutException e) {
            rtnString = "超时异常，请检查代码中是否使用Thread.sleep方法。（单次编译运行最多支持3秒）";
        } finally {
            if (null != map) {
                rtnString = (String) map.get("result");
            }
        }
        return rtnString;
    }

}
